package com.assets.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Worker;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.demo.WaveSwipeRefreshLayout;
import com.assets.Adapter.Public_list_item_Adapter;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scrap.Scrap_Add;
import com.assets.Scrap.Scrap_dispose;
import com.assets.bean.list_item_apter;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/3/11.
 */

public class Scrap extends Fragment {
    private ImageView imageView, screen;
    private ImageView add;
    String st = "";
    private String deptid;
    private SlideSideMenuExampleActivity mainActivity;
    private ListView lv_list;
    private String url = "http://" + Url.IP + "/api/scrapQuery";
    WaveSwipeRefreshLayout mWaveSwipeRefreshLayout;
    List<Map<String, Object>> condemned_stores = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> obsolescent = new ArrayList<Map<String, Object>>();
    List<Map<String, Object>> applying = new ArrayList<Map<String, Object>>();

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    private static final String TAG = "这个是报废页面";

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.scrap, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mainActivity = (SlideSideMenuExampleActivity) getActivity();
        SharedPreferences mm = mainActivity.getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        deptid = mm.getString("id", "");
        init();

    }

    private void init() {
        screen = (ImageView) mainActivity.findViewById(R.id.screen);

        TextView title = mainActivity.findViewById(R.id.title_text);
        title.setText("报废");
        screen.setOnClickListener(v -> new AlertView("筛选", null, "取消", new String[]{"全部"}, new String[]{"申请中", "待报废", "已报废"}, mainActivity, AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    //适配器，刚刚重写的！
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity, list);
                    lv_list.setAdapter(re_ad);
                }
                if (position == 1) {
                    applying.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("state").equals("申请中")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv", "报废单号");
                            map.put("creator_tv", "报废人");
                            map.put("sum_tv", "创建人");
                            map.put("state_tv", "状态");
                            map.put("scope_tv", "部门");
                            map.put("Date_created_tv", "创建日期");
                            map.put("Inventory_date_tv", "报废日期");
                            map.put("state", list.get(i).get("state"));
                            map.put("scope", list.get(i).get("scope"));
                            map.put("odd", list.get(i).get("odd"));
                            map.put("Date_created", list.get(i).get("Date_created"));
                            map.put("creator", list.get(i).get("creator"));
                            map.put("sum", list.get(i).get("sum"));
                            map.put("Inventory_date", list.get(i).get("Inventory_date"));
                            applying.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity, applying);
                    lv_list.setAdapter(re_ad);

                }
                if (position == 2) {
                    obsolescent.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("state").equals("待报废")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv", "报废单号");
                            map.put("creator_tv", "报废人");
                            map.put("sum_tv", "创建人");
                            map.put("state_tv", "状态");
                            map.put("scope_tv", "部门");
                            map.put("Date_created_tv", "创建日期");
                            map.put("Inventory_date_tv", "报废日期");
                            map.put("state", list.get(i).get("state"));
                            map.put("scope", list.get(i).get("scope"));
                            map.put("odd", list.get(i).get("odd"));
                            map.put("Date_created", list.get(i).get("Date_created"));
                            map.put("creator", list.get(i).get("creator"));
                            map.put("sum", list.get(i).get("sum"));
                            map.put("Inventory_date", list.get(i).get("Inventory_date"));
                            obsolescent.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity, obsolescent);
                    lv_list.setAdapter(re_ad);

                }
                if (position == 3) {
                    condemned_stores.clear();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).get("state").equals("已报废")) {
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("odd_tv", "报废单号");
                            map.put("creator_tv", "报废人");
                            map.put("sum_tv", "创建人");
                            map.put("state_tv", "状态");
                            map.put("scope_tv", "部门");
                            map.put("Date_created_tv", "创建日期");
                            map.put("Inventory_date_tv", "报废日期");
                            map.put("state", list.get(i).get("state"));
                            map.put("scope", list.get(i).get("scope"));
                            map.put("odd", list.get(i).get("odd"));
                            map.put("Date_created", list.get(i).get("Date_created"));
                            map.put("creator", list.get(i).get("creator"));
                            map.put("sum", list.get(i).get("sum"));
                            map.put("Inventory_date", list.get(i).get("Inventory_date"));
                            condemned_stores.add(map);
                        }
                    }
                    Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity, condemned_stores);
                    lv_list.setAdapter(re_ad);
                }

            }
        }).show());
        add = (ImageView) getActivity().findViewById(R.id.add);
        add.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), Scrap_Add.class);
            startActivity(intent);
        });
        lv_list = (ListView) getActivity().findViewById(R.id.lv_Receive);
        lv_list.setOnItemClickListener((adapterView, view, i, l) -> {
            String str = String.valueOf(lv_list.getAdapter().getItem(i));
            String[] strs = str.split(",");
            Intent intent = new Intent(getActivity(), Scrap_dispose.class);
            intent.putExtra("details", "details");
            intent.putExtra("scrapId", strs[1].toString());
            startActivity(intent);
        /*    if (strs[0].toString().equals("待报废")||strs[0].toString().equals("已报废")) {
                Intent intent = new Intent(getActivity(), Scrap_dispose.class);
                intent.putExtra("scrapId", strs[1].toString());
                startActivity(intent);
            }*/
        });
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
        imageView.setOnClickListener((View.OnClickListener) v -> {
            SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
            mSlideSideMenu.toggle();
        });
        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) getActivity().findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE);//设置水滴中旋转动画的颜色，参数1:水滴落下过程中的颜色，参数2:水滴已经落下后的颜色
        mWaveSwipeRefreshLayout.setWaveColor(0xFF3794fc);//设置水滴样色
        //mWaveSwipeRefreshLayout.setMaxDropHeight(1500);//设置最大下拉高度
        mWaveSwipeRefreshLayout.setOnRefreshListener(new WaveSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {//模拟3秒的加载过程
                    @Override
                    public void run() {
                        load();
                        //接下来可以刷新ListView
                    }
                }, 1200);
            }

        });
    }

    private void load() {
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        List<com.assets.room.entity.Scrap> scraps = MyDataBase.init(mainActivity).scrapService().getAllData();
        for (com.assets.room.entity.Scrap scrap : scraps) {
            if(!scrap.getStatus().equals("4")) {
                Map<String, Object> map = new HashMap<String, Object>();
//                Worker worker = MyDataBase.init(mainActivity).workerService().getWorkerById(scrap.getUserId())/*workerService.getById(scrap.getUserId())*/;
//                if(worker!=null) {
//                    scrap.setUserId(worker.getName());
//                }
//                Worker worker2 = MyDataBase.init(mainActivity).workerService().getWorkerById(scrap.getUserId())/*workerService.getById(scrap.getOperator())*/;
//                if(worker2!=null) {
//                    scrap.setOperator(worker2.);
////                }

                map.put("scrapId", scrap.getScrapId());
                map.put("deptId", scrap.getDeptId());
                map.put("userId", scrap.getUserId());
                map.put("operator", scrap.getOperator());
                map.put("status", scrap.getStatus());
                map.put("redate", scrap.getRedate());
                map.put("createdate", scrap.getCreatedate());
                maps.add(map);
            }
        }
        Log.d("我是马牛逼", "new Gson().toJson(maps): " + new Gson().toJson(maps));
        showResponse(new Gson().toJson(maps));

//        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    OkHttpClient client = new OkHttpClient
//                            .Builder()
//                            .hostnameVerifier(new AllowAllHostnameVerifier())
//                            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
//                            .connectTimeout(10, TimeUnit.SECONDS)//连接超时
//                            .readTimeout(500, TimeUnit.SECONDS)
//                            .build();
//                    RequestBody requestBody = new FormBody.Builder()
//                            .add("userId", Since_case.getInstance().getUserId())
//                            .build();
//                    Request request = new Request.Builder()
//                            .url(url)
//                            .post(requestBody).build();
//                    Response response = client.newCall(request).execute();
//                    String responseData = response.body().string();
//                    LogUtils.d(responseData);
//                    showResponse(responseData);//解析
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//
//
//            }
//        }.start();
    }

    private void showResponse(final String responseData) {
        mainActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("我是大牛逼", "responseData: " + responseData);
                if (responseData.equals("[]")) {
                    Toast.makeText(mainActivity, "无报废单", Toast.LENGTH_SHORT).show();
                }
                list.clear();
                mWaveSwipeRefreshLayout.setRefreshing(false);//停止加载动画
                Gson gson = new Gson();
                List<list_item_apter> userList = null;
                try {
                    userList = gson.fromJson(responseData, new TypeToken<List<list_item_apter>>() {
                    }.getType());
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mainActivity, "数据异常", Toast.LENGTH_SHORT).show();
                }
                if (userList == null) {
                    Toast.makeText(mainActivity, "数据异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < userList.size(); i++) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("odd_tv", "报废单号");
                    map.put("sum_tv", "操作人");
                    map.put("state_tv", "状态");
                    map.put("scope_tv", "报废单位");
                    map.put("creator_tv", "报废人");
                    map.put("Date_created_tv", "申请时间");
                    map.put("Inventory_date_tv", "报废日期");
                    map.put("odd", userList.get(i).getScrapId());//报废单号
                    map.put("Date_created", userList.get(i).getRedate().substring(0, 10));//申请时间
                    map.put("creator", MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getUserId()) == null ? "暂无此人": MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getUserId()).getName()/*"123123"*/);          //报废人
                    map.put("sum", MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getUserId()) == null ? "暂无此人" : MyDataBase.init(mainActivity).userDao().getUserById(userList.get(i).getUserId()).getName());//getOperator// 操作人
                    map.put("Inventory_date", userList.get(i).getCreatedate());
                    map.put("scope", MyDataBase.init(mainActivity).deptDao().getDeptById(userList.get(i).getDeptId()) == null ? "" : MyDataBase.init(mainActivity).deptDao().getDeptById(userList.get(i).getDeptId()).getSimpleName());
//                    if (userList.get(i).getCreatedate().equals("")) {
//                        map.put("Inventory_date", ""/*userList.get(i).getCreatedate()*/);
//                    } else {
//                        map.put("Inventory_date", ""/*userList.get(i).getCreatedate().substring(0, 10)*/);
//                        map.put("scope", userList.get(i).getDeptId());
//                    }
                    String zt = "";
                    String state = userList.get(i).getStatus();
                    if (!state.equals("5")) {
                        if (state.equals("0")) {
                            zt = "申请中";
                        } else if (state.equals("3")) {
                            zt = "已报废";
                        } else {
                            zt = "驳回";
                        }
                        map.put("state", zt);
                        list.add(0, map);
                    }
                }
                Public_list_item_Adapter re_ad = new Public_list_item_Adapter(mainActivity, list);
                lv_list.setAdapter(re_ad);
            }
        });
    }

    @Override
    public void onStart() {
        Timer timer = new Timer();//实例化Timer类
        timer.schedule(new TimerTask() {
            public void run() {
                load();
                this.cancel();
            }
        }, 300);//五百毫秒
        super.onStart();
    }
}
